package com.isoft.src.main.java.service;

import com.isoft.src.main.java.model.Product;
import com.isoft.src.main.java.util.ProductFileHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProductService {
    private Map<String, Product> products = new HashMap<>();

    public ProductService() {
        loadProducts();
    }

    private void loadProducts() {
        List<Product> productList = ProductFileHandler.loadProducts();
        for (Product product : productList) {
            products.put(product.getId(), product);
        }
    }

    private void saveProducts() {
        ProductFileHandler.saveProducts(new ArrayList<>(products.values()));
    }

    public void addProduct(Product product) {
        products.put(product.getId(), product);
        saveProducts();
    }

    public void removeProduct(String id) {
        products.remove(id);
        saveProducts();
    }

    public void updateProduct(Product product) {
        products.put(product.getId(), product);
        saveProducts();
    }

    public Map<String, Product> getAllProducts() {
        return products;
    }
}
